﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SurfaceAd.Assistant;
using SurfaceAd.Common;
using SurfaceAd.Entities;
using SurfaceAd.Entities.Ad;
using Windows.UI;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;

/**
 * 创建时间：2014/9/28 10:27:14
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace SurfaceAd.Views
{
    internal sealed class WebViewPage
    {
        public event EventHandler OnCloseIconHandler, OnOpenAdContentScreenHandler;

        private Popup popup;
        private Grid gridMain;
        private WebView webViewMain;
        private StackPanel spProgressInfo;
        private AdResponse adContent;

        public WebViewPage()
        {
            if (popup == null)
            {
                popup = new Popup();
            }
            OrientationScreenSize screenSize = OrientationScreenSizeHelper.GetScreenSize();
            popup.Height = screenSize.Height;
            popup.Width = screenSize.Width;
        }

        public WebViewPage(AdResponse adContent)
            : this()
        {
            this.adContent = adContent;
            //
            this.gridMain = new Grid();
            this.webViewMain = new WebView();
            this.webViewMain.Height = this.popup.Height;
            this.webViewMain.Width = this.popup.Width;
            //
            this.webViewMain.NavigationStarting += webViewMain_NavigationStarting;
            this.webViewMain.ContentLoading += webViewMain_ContentLoading;
            this.webViewMain.DOMContentLoaded += webViewMain_DOMContentLoaded;
            this.webViewMain.NavigationCompleted += webViewMain_NavigationCompleted;
            //
            //进度提示栏
            this.DrawProgressInfoToWebViewPage();            
            //
            this.gridMain.Children.Add(this.webViewMain);
            this.gridMain.Children.Add(this.spProgressInfo);
            //
            this.OpenWebViewPage();
        }

        /// <summary>
        /// 绘制打开目标地址的进度信息
        /// </summary>
        void DrawProgressInfoToWebViewPage()
        {
            this.spProgressInfo = new StackPanel() { Height = 80, Width = 80, Background = new SolidColorBrush(Colors.Transparent), Orientation = Orientation.Vertical };
            this.spProgressInfo.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center;
            this.spProgressInfo.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center;
            ProgressRing progressRing = new ProgressRing() { Height = 30, Width = 30, IsActive = true, Background = new SolidColorBrush(Colors.Transparent), Visibility = Windows.UI.Xaml.Visibility.Visible };
            progressRing.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center;
            progressRing.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center;
            TextBlock txtInfo = new TextBlock() { Text = "正在加载中", FontSize = 16 };
            this.spProgressInfo.Children.Add(progressRing);
            this.spProgressInfo.Children.Add(txtInfo);
        }

        /// <summary>
        /// 绘制关闭Popup的Icon
        /// </summary>
        void DrawCloseIconToWebViewPage()
        {
            try
            {
                double repeateSize = 40;
                Image adCloseIcon = new Image() { Height = repeateSize, Width = repeateSize, Stretch = Stretch.Uniform, Margin = new Windows.UI.Xaml.Thickness(0, 10, 10, 0) };
                adCloseIcon.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///SurfaceAdImages/close.png"));
                adCloseIcon.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
                adCloseIcon.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                //关闭广告位事件
                adCloseIcon.Tapped += delegate(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
                {
                    try
                    {
                        this.CloseWebViewPage();
                    }
                    catch
                    {
                        LogHelper.LogError("内容查看窗口被关闭！", this.GetType(), "DrawCloseIconToWebViewPage");
                    }
                };
                this.gridMain.Children.Add(adCloseIcon);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), "DrawCloseIconToWebViewPage");
            }
        }

        void webViewMain_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
        {
            LogHelper.LogInfo("webViewMain_DOMContentLoaded:\t" + args.ToString());

        }

        void webViewMain_ContentLoading(WebView sender, WebViewContentLoadingEventArgs args)
        {
            LogHelper.LogInfo("webViewMain_ContentLoading:\t" + args.ToString());
        }

        void webViewMain_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            LogHelper.LogInfo("webViewMain_NavigationCompleted:\t" + args.WebErrorStatus.ToString());
            //
            this.spProgressInfo.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            //关闭按钮
            this.DrawCloseIconToWebViewPage();
            if (this.OnOpenAdContentScreenHandler != null)
            {
                this.OnOpenAdContentScreenHandler(null, new EventArgs());
            }

            if (args.IsSuccess)
            {
                //this.OpenWebViewPage();
            }
            //如果有跳转，就直接关闭这个Popup，否则必须按两次BackKeyPress才会返回至应用程序
            if (args.WebErrorStatus == Windows.Web.WebErrorStatus.RedirectFailed)
            {
                this.CloseWebViewPage();
            }
        }

        void webViewMain_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            this.spProgressInfo.Visibility = Windows.UI.Xaml.Visibility.Visible;
            LogHelper.LogInfo("webViewMain_NavigationStarting:\t" + args.ToString());
        }


        /// <summary>
        /// 屏幕方向变更时Popup及其子元素也要变更
        /// </summary>
        public void OrientationChanged()
        {
            if (popup != null)
            {
                OrientationScreenSize screenSize = OrientationScreenSizeHelper.GetScreenSize();
                popup.Height = screenSize.Height;
                popup.Width = screenSize.Width;
                //
                this.webViewMain.Height = this.popup.Height;
                this.webViewMain.Width = this.popup.Width;
            }
        }

        /// <summary>
        /// 必须先保证Popup正常显示
        /// </summary>
        private void OpenWebViewPage()
        {
            try
            {
                if (this.popup != null)
                {
                    this.popup.Child = this.gridMain;
                    string destinationUrl = new AdResponseHelper().GetJumpData(this.adContent);
                    if (string.IsNullOrWhiteSpace(destinationUrl))
                    {
                        this.CloseWebViewPage();
                        return;
                    }                   
                    this.popup.IsOpen = true;
                    this.webViewMain.Navigate(new Uri(destinationUrl));
                    //
                    //应用商店                    
                    //this.webViewMain.Navigate(new Uri("http://www.windowsphone.com/zh-cn/store/app/iq-mission/31701cfb-1d1a-487c-bf21-bd8e7a715ebb"));//args.WebErrorStatus=RedirectFailed                
                    //this.webViewMain.Navigate(new Uri("http://www.baidu.com"));
                    //this.webViewMain.Navigate(new Uri("http://www.mediabris.com"));
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), "OpenWebViewPage");
            }
        }


        public void CloseWebViewPage()
        {
            if (this.popup != null)
            {
                try
                {
                    this.popup.IsOpen = false;
                    this.popup.Child = null;
                    if (this.OnCloseIconHandler != null)
                    {
                        //在此事件中必须使用-=来移除OnCloseIconHandler事件，否则会有死循环
                        this.OnCloseIconHandler(null, new EventArgs());
                    }
                }
                catch (Exception err)
                {
                    LogHelper.LogError(err.ToString(), this.GetType(), "CloseWebViewPage");
                }
            }
        }
    }
}
